# -*- coding: utf-8 -*-
# @Author : Ryhn
# -*- coding: utf-8 -*-
# @Time : 2023/9/22 0022 10:59
# @Author : Ryhn
# @File : Email.py
import smtplib
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import loguru
from starlette.responses import Response


class Email_company():
	'''
	邮件服务器类
	'''
	def __init__(self, url: str, port: int):
		"""
		邮件服务器连接地址配置
		:param url: 邮件地址
		:type url: str
		:param port: 邮件端口
		:type port: int
		"""
		self.url = url
		self.port = port
		self.smtp = None

	def connect(self):
		'''
		连接邮件服务器
		:return:
		:rtype:
		'''
		try:
			print(f"尝试连接{self.url}邮件服务器")
			self.smtp = smtplib.SMTP_SSL(self.url, self.port)
		except:
			print(f"未成功连接上{self.url}邮件服务器的{self.port}端口")

class Email_user():
	'''
	邮件发送者类
	'''
	_login = None  # 验证是否登录的属性
	def __init__(self, Email_company: smtplib.SMTP_SSL, username: str, password: str):
		'''
		邮件账户配置
		:param Email: Email实体类
		:type Email: object
		:param username:用户名
		:type username: str
		:param password: 账户密码（一般在邮件设置中可以找到对应的密码配置）
		:type password: str
		'''
		self.Email_company = Email_company
		self.username = username
		self.password = password

	def login(self):
		'''
		邮件登录
		:return:
		:rtype:
		'''
		if not self._login:
			try:
				self.Email_company.login(self.username, self.password)
				self._login = True
				print("邮箱登录成功")
			except:
				print("邮箱登录失败，账户或密码错误")
		else:
			return True

	def test_send(self):
		'''
		测试邮件发送
		:return:
		:rtype:
		'''
		self.login()
		try:
			self.Email_company.sendmail(self.username, self.username, msg=("测试:邮件是否能正常发送").encode(encoding="utf-8"))
			print("邮件发送成功")
		except smtplib.SMTPException:
			print("邮件发送失败")
			print(traceback.print_exc())

	def send_Email(self, to_addrs: list , msg):
		'''
		邮件发送
		:param msg: 邮件内容
		:type msg:
		:return:
		:rtype:
		'''
		self.login()
		try:
			self.Email_company.sendmail(self.username, to_addrs, msg=msg)
			print("邮件发送成功")
		except smtplib.SMTPException:
			print("邮件发送失败")
			loguru.logger.error(traceback.print_exc())
			return Response(status_code=400, content="邮箱登录失败导致邮件无法发送")

class Email_msg():
	'''
	邮件内容类
	'''
	def __init__(self):
		self.msg = MIMEMultipart('related')
	def title(self, From: str, To: str, Subject: str):
		'''
		设置邮件标题内容
		:param From: 发出者
		:type From: str
		:param To: 收件者
		:type To: str
		:param Subject: 邮件主题
		:type Subject: str
		:return:
		:rtype:
		'''
		self.msg['From'] = Header(From, 'utf-8')
		self.msg['To'] = Header(To, 'utf-8')
		self.msg['Subject'] = Header(Subject, 'utf-8')

	def text(self, mail_msg: str):
		'''
		设置邮件内容(html格式)
		:param mail_msg:邮件内容
		:type mail_msg:str
		:return:
		:rtype:
		'''
		msgAlternative = MIMEMultipart('alternative')
		self.msg.attach(msgAlternative)
		msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
		return self.msg.as_string()

def email_make(title_dict, text):
	'''
	制作email
	:param title_dict: {"From": ,"To": ,"Subject": }
	:type title_dict: dict
	:param text:
	:type text:
	:return: sting(email)
	:rtype:
	'''
	email_message = Email_msg()
	email_message.title(**title_dict)
	return email_message.text(text)

def send_robot_email(Subject: str, message, username, password, receiver, port=465, url="smtp.exmail.qq.com",):
	'''
	发送邮件功能实现
	:return:
	:rtype:
	'''
	# todo:连接邮件服务器
	Email = Email_company(url, port)
	Email.connect()
	# todo:邮件账户登录
	email_login = Email_user(Email.smtp, username, password)
	# todo:邮件制作
	email_ = email_make({"From": "测试团队", "To": "部门内部", "Subject": Subject},
						message)
	# # todo:发送对应邮件
	email_login.send_Email(receiver.split(','), email_)